import { useState, useEffect, useRef } from 'react'
import { Card, Button, Table, Tag, Switch, message, Popconfirm, Drawer, Form, Input, Select, Avatar } from 'antd'
// import { getUserLevelList, addUserLevel, editUserLevel, delUserLevel, changStatus } from '@/api/level'
import { getUserList, addUser, editUser, delUser, changStatus } from '@/api/user'
import { UserOutlined, PlusCircleFilled, DeleteOutlined } from '@ant-design/icons'
import ChooseImage from '@/components/ChooseImage'

function User() {
  const [userList, setuserlList] = useState([])
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const [keyword, setKeyword] = useState('')
  const [levelList, setLevelList] = useState([])
  useEffect(() => {
    getList()
  }, [page])
  const getList = () => {
    getUserList(page, keyword).then(res => {
      if (res.status === 200) {
        setuserlList(res.data.list)
        setTotal(res.data.totalCount)
        setLevelList(res.data.user_level)
      }
    })
  }
  const switchChange = (status: boolean, id: number) => {
    changStatus(id, { status: !status }).then(res => {
      if (res.status === 200) {
        getList()
        message.success('修改成功')
      } else {
        message.error('修改失败')
      }
    })
  }
  const delLevel = (id: number) => {
    delUser(id).then(res => {
      if (res.status === 200) {
        getList()
        message.success('删除成功')
      } else {
        message.error('删除失败')
      }
    })
  }
  const columns = [
    {
      title: '会员',
      render: (data: any) => (
        <div className='flex2 centerFlex' style={{ maxWidth: '150px' }}>
          <Avatar size='large' src={data.avatar} icon={<UserOutlined />} />
          <div className='ml-10'>
            <p>{data.username}</p>
            <p>ID{data.id}</p>
          </div>
        </div>
      )
    },
    {
      title: '会员等级',
      render: (data: any) => <>{<p>{data.user_level ? data.user_level.name : '-'}</p>}</>
    },
    {
      title: '状态',
      render: (data: any) => (
        <div className='flex2 centerFlex' style={{ maxWidth: '150px' }}>
          <Switch
            checked={data.status}
            onChange={() => {
              switchChange(data.status, data.id)
            }}
          ></Switch>
        </div>
      )
    },
    {
      title: '操作',
      render: (data: any) => (
        <div className='flex2 centerFlex' style={{ maxWidth: '150px' }}>
          <Tag
            color='lime'
            onClick={() => {
              editBtn(data)
            }}
          >
            修改
          </Tag>
          <Popconfirm
            title='注意'
            description='你确认要删除该等级吗？'
            onConfirm={() => {
              delLevel(data.id)
            }}
            okText='确认'
            cancelText='取消'
          >
            <Tag color='red'>删除</Tag>
          </Popconfirm>
        </div>
      )
    }
  ]
  // 添加修改弹框
  const [openDrawer, setOpenDrawer] = useState(false)
  const [editId, setEditId] = useState(0)
  const [form] = Form.useForm()
  const addBtn = () => {
    setEditId(0)
    setOpenDrawer(true)
    form.resetFields()
  }
  const editBtn = (data: any) => {
    setOpenDrawer(true)
    setEditId(data.id)
    form.setFieldsValue({
      discount: data.discount,
      level: data.level,
      max_price: data.max_price,
      max_times: data.max_times,
      name: data.name,
      status: data.status
    })
  }
  const saveAddLevelBtn = () => {
    form.validateFields().then(values => {
      if (editId !== 0) {
        editUser(editId, { ...values, avatar: imgUrl }).then(res => {
          if (res.status === 200) {
            message.success('修改成功')
            getList()
            setOpenDrawer(false)
          }
        })
        return
      }
      addUser({ ...values, avatar: imgUrl }).then(res => {
        if (res.status === 200) {
          message.success('添加成功')
          getList()
          setOpenDrawer(false)
        }
      })
    })
  }
  const chooseImgRef = useRef<any>(null)
  const [imgUrl, setImgUrl] = useState('')
  const getImgUrl = (url: string) => {
    setImgUrl(url)
  }
  const openImgDrawer = () => {
    chooseImgRef.current.showModal()
  }
  const btn = (
    <div style={{ textAlign: 'right' }}>
      <Button type='primary' size='large' onClick={saveAddLevelBtn}>
        提交
      </Button>
      <Button
        size='large'
        style={{ marginLeft: '15px' }}
        onClick={() => {
          setOpenDrawer(false)
        }}
      >
        取消
      </Button>
    </div>
  )
  return (
    <>
      <Card>
        <Button onClick={addBtn}>新增用户</Button>
        <Table
          columns={columns}
          dataSource={userList}
          rowKey='id'
          pagination={{ total }}
          onChange={(e: any) => {
            setPage(e.current)
          }}
        />
      </Card>
      <Drawer
        title={editId === 0 ? '添加用户' : '修改用户'}
        onClose={() => {
          setOpenDrawer(false)
        }}
        open={openDrawer}
        footer={btn}
      >
        <Form form={form}>
          <Form.Item name='username' label='用户名' rules={[{ required: true, message: '请输入用户名' }]}>
            <Input placeholder='请输入用户名' />
          </Form.Item>
          <Form.Item name='password' label='密码' rules={[{ required: true, message: '请输入密码' }]}>
            <Input placeholder='请输入密码' />
          </Form.Item>
          <Form.Item name='nickname' label='昵称' rules={[{ required: true, message: '请输入昵称' }]}>
            <Input placeholder='请输入昵称' />
          </Form.Item>
          <Form.Item label='头像' name='avatar'>
            {imgUrl && (
              <div style={{ position: 'relative' }}>
                <img src={imgUrl} className='imgItem' alt='' style={{ width: 120, height: 120, objectFit: 'cover' }} />
                <div className='delImage'>
                  <DeleteOutlined
                    style={{ color: '#fff', cursor: 'pointer', fontSize: '20px' }}
                    onClick={() => {
                      setImgUrl('')
                    }}
                  />
                </div>
              </div>
            )}
            <div className='addPic' onClick={openImgDrawer}>
              <PlusCircleFilled />
            </div>
          </Form.Item>
          <Form.Item name='user_level_id' label='会员等级' rules={[{ required: true, message: '请选择会员等级!' }]}>
            <Select placeholder='请选择会员等级' style={{ width: 180 }} options={levelList} fieldNames={{ label: 'name', value: 'id' }} />
          </Form.Item>
          <Form.Item name='phone' label='手机号'>
            <Input placeholder='请输入手机号' />
          </Form.Item>
          <Form.Item
            name='email'
            label='邮箱'
            rules={[
              {
                type: 'email',
                message: '请输入正确的邮箱'
              }
            ]}
          >
            <Input placeholder='请输入邮箱' />
          </Form.Item>
          <Form.Item name='status' label='是否启用' rules={[{ required: true }]} initialValue={true}>
            <Switch></Switch>
          </Form.Item>
        </Form>
      </Drawer>
      <ChooseImage getImgUrl={getImgUrl} ref={chooseImgRef} />
    </>
  )
}
export default User
